﻿using System;
using System.Linq;
using ProjetoComperio.DataLayer.Entities;
using ProjetoComperio.DataLayer.Infra;
using ProjetoComperio.Framework.Extensions;

namespace ProjetoComperio.BusinessLogicLayer
{
    public class ProjectBLL : ComperioDataObject
    {

        private ContributionBLL _contributionBLL; 
        

        /// <summary>
        /// This method inserts a new project
        /// </summary>
        /// <param name="project"></param>
        public void Create(Project project)
        {
            DbContext.Contributions.Add(project);
            DbContext.SaveChanges(); 
        }

        /// <summary>
        /// This method edits a project
        /// </summary>
        /// <param name="project"></param>
        public void Edit(Project project)
        {
            Project original = this.RetrieveProject(project.ContributionID);
            original.CopyValuesFrom(project);
            DbContext.SaveChanges();

        }

        /// <summary>
        /// This method returns all projects from db
        /// </summary>
        /// <returns></returns>
        public IQueryable<Project> RetrieveProjects()
        {
            return DbContext.Contributions.OfType<Project>();
        }

        /// <summary>
        /// Retrieves all projects related to the academicPersonID
        /// </summary>
        /// <param name="academicPersonID"></param>
        /// <returns></returns>
        public IQueryable<Project> RetrieveProjects(int academicPersonID)
        {
            return new ContributionBLL().RetrieveAcademicPersonContributions(academicPersonID).OfType<Project>();
        }

        /// <summary>
        /// This method retrieve a specific project
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public Project RetrieveProject(Int32 contributionID)
        {
            return DbContext.Contributions.OfType<Project>().Where(project => project.ContributionID == contributionID).FirstOrDefault();
        }

        /// <summary>
        /// This method returns the projects registered on the last week
        /// </summary>
        /// <returns></returns>
        public IQueryable<Project> RetrieveRecentProjects()
        {
            var dateFromLastWeek = DateTime.Now.AddDays(-7);

            return DbContext.Contributions.OfType<Project>().Where(project => project.RegisterDate >= dateFromLastWeek);
        }
    }
}
